﻿<?php
function runTaskKsend(){
	writeKSendLog("");//d41d8cd98f00b204e9800998ecf8427e
	writeKSendLog(" 新的请求：请求密码->".$_GET['pw']);//d41d8cd98f00b204e9800998ecf8427e
	writeKSendLog(" 新的请求：配置密码->".md5(getKSendConfigVal('KMISSION_RUNPW')));//d41d8cd98f00b204e9800998ecf8427e
	
	if($_GET['pw']!=md5(getKSendConfigVal('KMISSION_RUNPW'))){
		writeKSendLog(" 新的请求：密码错误！");//d41d8cd98f00b204e9800998ecf8427e
		exit;
	}
	writeKSendLog(" 配置参数： KMISSION_RUNPW=".getKSendConfigVal('KMISSION_RUNPW'));
	writeKSendLog(" 配置参数： KMISSION_INTERVAL=".getKSendConfigVal('KMISSION_INTERVAL')."秒");
	$kmsd = getKSendConfigVal('KMISSION_SHUTDOWN');
	if(!$kmsd)writeKSendLog(" 配置参数： KMISSION_SHUTDOWN=开启");
	else writeKSendLog(" 配置参数： KMISSION_SHUTDOWN=关闭");
	//$no = service('Coupon')->countByMobile('13810388527',null);
	ignore_user_abort(); // run script in background
	set_time_limit(0); // run script forever
	$interval=getKSendConfigVal('KMISSION_INTERVAL'); // do every 15 minutes...
	$ifstop = false;
	do{
		if(getKSendConfigVal('KMISSION_SHUTDOWN')){
			writeKSendLog('定时任务停止！');
			exit;
		}
		//writeKSendLog($no);
		$sendedcoupon = doKSend();
		if(empty($sendedcoupon))$ifstop=true;
		sleep($interval); // wait 15 minutes
	}while(!$ifstop);
	writeKSendLog('定时任务结束！');
}

function writeKSendLog($msg){
	$fp = @fopen("./task/sendLog.txt", "a+");
	//fwrite($fp, date("Y-m-d H:i:s") .' '. $no." 让PHP定时运行吧！\n");
	fwrite($fp, date("Y-m-d H:i:s") .' - '.$msg." \n");
	fclose($fp);
}

function getKSendConfigVal($name){
	$config = include "./task/sendConfig.php"; 
	//dump($config);
	return $config[$name];
}


function doKSend(){
	$couponlist = service('Coupon')->selectTobeSend(null,null,100);
	$sendcenter = service('SendCenter');
	$senData = $sendcenter->parseCouponSendData($couponlist);
	$i=1;
	writeKSendLog("发送数据：共".count($senData['center_senddata'])."条");
	foreach($senDate['center_senddata'] as $vo){
		writeKSendLog("发送数据：第".$i."条");
		writeKSendLog("发送数据：".parseAry2Str($vo));
		$i=1+$i;
	}
	$sendcenter->send($senData);
	return $couponlist;
}
?>
